package com.project.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.client.domain.AreaInfoEntity;
import com.project.client.dto.AreaInfoTreenode;
import com.project.client.mapper.AreaInfoMapper;
import com.project.client.service.AreaInfoService;
import com.project.common.core.redis.RedisCache;
import com.project.common.service.BaseServiceImpl;
import com.project.common.utils.ConvertUtils;
import com.project.common.utils.treenode.TreeNodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class AreaInfoServiceImpl extends BaseServiceImpl<AreaInfoMapper, AreaInfoEntity> implements AreaInfoService {
    @Autowired
    private RedisCache redisCache;

    @Override
    public AreaInfoEntity selectById(Long id) {
        return baseDao.selectById(id);
    }

    @Override
    public AreaInfoEntity selectByCode(String areaCode) {
        return baseDao.selectByCode(areaCode);
    }

    @Override
    public AreaInfoEntity selectByName(String name) {
        return baseDao.selectByName(name);
    }

    @Override
    public List<AreaInfoEntity> selectByCodes(String areaCodes) {
        return baseDao.selectByCodes(areaCodes);
    }


    @Override
    public List<AreaInfoTreenode> tree(Long level) {
        return tree(0l, 0l, level);
    }

    @Override
    public List<AreaInfoTreenode> tree(Long startParentId, Long startLevel, Long endLenel) {
        String k = startLevel + "-" + endLenel;
        List<AreaInfoTreenode> tree = redisCache.getCacheObject(getCacheKey(k));
        if (tree == null) {
            List<AreaInfoEntity> list = baseDao.selectByLevel(startLevel,endLenel);
            tree = TreeNodeUtil.bulid(ConvertUtils.sourceToTarget(list, AreaInfoTreenode.class), startParentId.longValue(), endLenel.intValue());
            redisCache.setCacheObject(getCacheKey(k), tree);
        }
        return tree;
    }

    @Override
    public List<AreaInfoEntity> selectByLevel(Long startLevel, Long endLenel) {
        return baseDao.selectByLevel(startLevel,endLenel);
    }

    @Override
    public void clearCache() {
        Collection<String> keys = redisCache.keys("sys_cache:area_cache:*");
        redisCache.deleteObject(keys);
    }

    private String getCacheKey(String k) {
        return "sys_cache:area_cache" + (k == null ? "ALL" : "" + k);
    }


}
